package com.maimao.goods.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.maimao.api.mall.goods.BrandApi;
import com.maimao.core.constant.AuthKey;
import com.maimao.core.constant.Constants;
import com.maimao.core.enums.ExceptionEnum;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.core.utils.PinYinUtils;
import com.maimao.goods.controller.base.BaseController;
import com.maimao.goods.service.BrandService;
import com.maimao.goods.utils.JvmCacheHolder;
import com.maimao.model.common.CommonCheckInput;
import com.maimao.model.common.StatusInput;
import com.maimao.model.goods.Brand;
import com.maimao.model.goods.input.BrandBindCateInput;
import com.maimao.model.goods.input.BrandSearchInput;
import com.maimao.model.user.sys.dto.DelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author MaoLin Wang
 * @date 2020/12/8 4:41 下午
 */
@RestController
public class BrandController extends BaseController implements BrandApi {

    @Autowired
    private BrandService brandService;

    @Override
    @PostMapping("/search")
    public Result<?> search(@RequestBody BrandSearchInput input,
                                      @RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "size", defaultValue = "5") Integer size) {

        return Result.okData(RespCode.OK, brandService.search(input, page, size));
    }

    @Override
    @GetMapping("/list")
    public Result<?> list() {
        return Result.okData(JvmCacheHolder.brandCache.values());
    }

    @Override
    @GetMapping("/client/name")
    public Result<?> selectNameById(@RequestParam("id") Long id) {
        if (id == null || id < 0) {
            return Result.notValid();
        }
        return Result.okData(brandService.selectNameById(id));
    }

    /**
     * 批量查询品牌
     */
    @Override
    @GetMapping("/client/brands/batch")
    public Result<?> selectByIdBatch(@RequestBody List<Long> brandIds) {
        if (brandIds == null || brandIds.size() <= 0) {
            return Result.notValid();
        }
        return Result.okData(brandService.selectByIdBatch(brandIds));
    }

    /**
     * 根据名称查询品牌
     */
    @Override
    @GetMapping("/client/queryByName")
    public Result<?> selectByName(@RequestParam("name") String name) {
        if (StrUtil.isEmpty(name)) {
            return Result.notValid();
        }
        return Result.okData(brandService.selectByName(name));
    }


    /**
     * 根据三级分类id查询该分类下的所有品牌
     */
    @Override
    @GetMapping("/cateBrand")
    public Result<?> cateBrands(@RequestParam("cid") Integer cid3) {
        if (cid3 == null || cid3 < 1) {
            return Result.notValid();
        }

        AuthUser authUser = checkAndGetAuthUser();
        return Result.okData(brandService.cateBrands(cid3, authUser.getType().contains(AuthKey.WEB_ENTERPRISE), authUser.getId2Long()));

    }

    @Override
    @GetMapping("/hot")
    public Result<?> hotBrand() {

        return Result.okData(brandService.hotBrand());
    }

    @Override
    @RequestMapping("/logo")
    public Result<?> findLogoById(@RequestParam("id") Integer id) {
        if (id == null) {
            return Result.notValid();
        }
        String logo = brandService.selectLogoById(id);
        return Result.okData(RespCode.OK, logo);
    }

    /**
     * 修改logo地址 key：logo value:logo地址 key：id  value: 品牌id
     */
    @Override
    @PostMapping("/update/logo")
    public Result<?> updateLogo(@RequestBody Map<String, String> data) {
        if (data == null) {
            return Result.notValid();
        }
        String brandId = data.get(Constants.ID);
        String logo = data.get("logo");
        if (StringUtils.isAnyEmpty(brandId, logo)) {
            return Result.notValid("参数非法");
        }
        brandService.updateLogo(Integer.parseInt(brandId), logo);
        return Result.ok(RespCode.OK, "修改成功");
    }

    /**
     * 更新基本信息 值：品牌名、描述、排序 自动生成拼音和首字母
     */
    @PostMapping("/update/base")
    @Override
    public Result<?> updateBase(@RequestBody Brand brand) {
        if (StringUtils.isEmpty(brand.getName())) {
            return Result.notValid("请输入品牌名");
        }
        if (brand.getId() == null | brand.getId() < 1) {
            return Result.notValid();
        }
        if (brand.getOrder() == null || brand.getOrder() < 1) {
            brand.setOrder(Constants.ONE);
        }
        brandService.updateBase(brand);
        return Result.ok(RespCode.OK, "修改成功");
    }

    /**
     * 批量修改状态
     */
    @Override
    @PostMapping("/update/status")
    public Result<?> updateStatusBatch(@Valid @RequestBody DelDto delDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        brandService.updateStatusBatch(delDto.getStatus(), delDto.getIds());
        return Result.ok(RespCode.OK, delDto.getStatus() == 1 ? "恢复成功" : "冻结成功");
    }

    /**
     * 加入或取消推荐
     */
    @Override
    @PostMapping("/updateRecommend")
    public Result<?> operRecommend(@Valid @RequestBody StatusInput statusInput, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        Integer status = statusInput.getStatus();
        if (!status.equals(Constants.STATUS_0) && !status.equals(Constants.STATUS_1)) {
            return Result.notValid("状态非法");
        }
        brandService.operRecommend(statusInput.getId(), status);
        return Result.ok(RespCode.OK, statusInput.getStatus() == 1 ? "加入成功" : "取消成功");
    }

    /**
     * 加入或取消热门
     */
    @Override
    @PostMapping("/updateHot")
    public Result<?> operHot(@Valid @RequestBody StatusInput statusInput, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        Integer status = statusInput.getStatus();
        if (!status.equals(Constants.STATUS_0) && !status.equals(Constants.STATUS_1)) {
            return Result.notValid("状态非法");
        }
        brandService.operHot(statusInput.getId(), statusInput.getStatus());

        return Result.ok(RespCode.OK, statusInput.getStatus() == 1 ? "加入成功" : "取消成功");
    }

    /**
     * 企业注册时申请 内部调用
     *
     * @param brand
     * @return
     */
    @PostMapping("/client/add")
    @Override
    public Result<?> addBrand(@RequestBody @Validated Brand brand) {
        if (addBrand0(brand)) {
            return Result.fail(ExceptionEnum.BRAND_EXIST_ERROR, false);
        }
        Long id = brandService.add(brand);
        return Result.okData(id);
    }

    /**
     * 商家申请品牌
     */
    @PostMapping("/add")
    public Result<?> addBrandFromWeb(@RequestBody Brand brand) {
        if (brand == null) {
            return Result.notValid();
        }
        if (StrUtil.isEmpty(brand.getName())) {
            return Result.notValid("品牌名不能为空");
        }
        AuthUser authUser = checkAndGetAuthUser();
        Brand boundBrand = brandService.selectByShop(authUser.getShopId());
        if (boundBrand != null) {
            return Result.notValid("您已绑定过品牌，每个店铺最多允许绑定一个品牌");
        }
        brand.setOwnerId(authUser.getId2Long());
        brand.setShopId(authUser.getShopId());
        if (addBrand0(brand)) {
            return Result.fail(ExceptionEnum.BRAND_EXIST_ERROR, false);
        }
        Long id = brandService.add(brand);
        return Result.okData(id);
    }

    private boolean addBrand0(@Validated @RequestBody Brand brand) {
        Brand target = brandService.selectByName(brand.getName());
        if (target != null) {
            return true;
        }
        brand.setHead(PinYinUtils.getHead(brand.getName()));
        brand.setPinyin(PinYinUtils.getPinYin(brand.getName()));
        brand.setOrder(1000);
        brand.setCreateTime(DateUtils.now());
        brand.setDesc(brand.getName());
        brand.setHot(0);
        brand.setRecommend(0);
        brand.setStatus(2);
        return false;
    }

    /**
     * 品牌审核
     */
    @PostMapping("/check")
    @Override
    public Result<?> checkBrand(@RequestBody @Validated CommonCheckInput input) {
        if (!input.getSuccess() && StrUtil.isEmpty(input.getReason())) {
            return Result.notValid("请填写驳回原因");
        }
        brandService.checkBrand(input.getId(), input.getShopId(), input.getSuccess(), input.getReason());
        return Result.ok("审核成功");
    }

    /**
     * 根据品牌主查询品牌
     */
    @PostMapping("/query-owner")
    @Override
    public Result<?> selectByOwner(@RequestParam("ownerId") Long ownerId) {
        Brand brand = brandService.selectByOwner(ownerId);
        return Result.okData(brand);
    }

    /**
     * 根据店铺ID查询品牌
     */
    @PostMapping("/queryBrandByShopId")
    public Result<?> queryBrandByShopId(@RequestParam("shopId") Long shopId) {
        Brand brand = brandService.selectByShop(shopId);
        return Result.okData(brand);
    }

    /**
     * 查询当前登录商家的品牌和品牌所在分类
     *
     * @return
     */
    @GetMapping("/shopBrandCate")
    @Override
    public Result<?> shopBrandCate() {
        AuthUser authUser = checkAndGetAuthUser();
        if (authUser.getType().contains(AuthKey.WEB_ENTERPRISE) || authUser.getType().contains(AuthKey.WEB_COMMON)) {
            Map<String, Object> res = brandService.shopBrandCate(authUser.getShopId());
            return Result.okData(res);
        }
        return Result.notValid("身份非法");
    }

    /**
     * 给品牌绑定分类
     */
    @Override
    @PostMapping("/brandBindCate")
    public Result<?> brandBindCate(@RequestBody @Validated BrandBindCateInput input) {

        if (ObjectUtil.isEmpty(input.getBindCategoryIds())) {
            return Result.notValid("请选择绑定的三级分类");
        }
        return brandService.brandBindCate(input);
    }

    public static void main(String[] args) {
        List<String> list = new LinkedList<>();
        list.add("1");
        list.add("");
        list.add("2");
        list.add("3");
        list.add("");
        System.out.println(Optional.ofNullable(null).orElse("1"));
//        System.out.println(list);
    }


}
